package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mango.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        // 1.查询今日佳人, 构造查询条件
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(1);

        // 2. 查询
        RecommendUser recommendUser = mongoTemplate.findOne(query,RecommendUser.class);
        return recommendUser;
    }

    @Override
    public PageResult queryRecommendation(Long userId, Integer page, Integer pagesize) {
        //1. 查询首页推荐，构造查询条件
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(0)
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(5)
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(10)
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(pagesize).skip((page - 1) * pagesize);
        //2. 分页查询: 当前页数据
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3. 统计
        long count = mongoTemplate.count(query, RecommendUser.class);
        //4. 创建分页对象并返回
        PageResult pageResult = new PageResult(page,pagesize,(int)count,recommendUserList);
        return pageResult;
    }
}
